<template>
  <div class="work-trend">
    <continer class="work-report">
      <template slot="search">
        <quickSearch
          :advForm="quickSearchForm"
          @QuickSearch="headerQuery"
        >
          <template slot="slotCom">
            <el-select style="margin-right:4px" v-model="trend" @change="handleTrendChange">
              <el-option
                v-for="item in trendList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select v-if="trend !== 3" v-model="time" @change="handleTimeChange">
              <el-option
                v-for="item in trendOptionList[trend]"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-date-picker
              v-else
              v-model="time"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDatePickerChange"
            >
            </el-date-picker>
          </template>
        </quickSearch>
      </template>
      <template slot="oprate">
        <el-button type="primary" size="mini" @click="refresh">刷新</el-button>
      </template>
      <template slot="content">
        <div class="data-report">数据报表</div>
        <div class="report-count">
          <div class="report">
            <div class="icon" style="background: #F2FFF4">
              <i class="V7_iconfont V7_iconxinjiangongdan" style="color:#69D279"></i>
            </div>
            <div class="title">新建工单</div>
            <div class="count">{{createCount}}</div>
          </div>
          <div class="report">
            <div class="icon" style="background: #F5FAFF">
              <i class="V7_iconfont V7_iconwanchenggongdan" style="color:#008BEE"></i>
            </div>
            <div class="title">完成工单</div>
            <div class="count">{{finishCount}}</div>
          </div>
          <div class="report">
            <div class="icon" style="background: #FFF9E9">
              <i class="V7_iconfont V7_iconzhongzhigongdan" style="color:#FFBF00"></i>
            </div>
            <div class="title">终止工单</div>
            <div class="count">{{endCount}}</div>
          </div>
        </div>
        <div class="charts-container">
          <div style="width:160px;background-color:#FBFBFB"></div>
          <div id="workTrend" class="charts"></div>
        </div>
        <div class="data-report">数据详情</div>
        <instiutionTable
          ref="tableRef"
          :pages="workTablePages"
          :instiutionTableData="workTableData"
          :instiutionTableHeader="workTableHeader"
        >
        </instiutionTable>
      </template>
    </continer>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref, Prop, Watch } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import quickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import { commonAction, deepClone } from '@/utils/common'
import { getNowFormatDate, getCurrentWeekFirstDay, getDateGap, getCurrentMonthFirstDay, getLastWeekData, getLastDate, lastMonthLast, lastMonthFirst, getMonthBetween } from './utils'
import * as echarts from 'echarts'
const workSource = [
  {
    label: '用户移动端',
    value: 1
  },
  {
    label: '网页端',
    value: 2
  },
  {
    label: '接口创建',
    value: 3
  }
]
@Component({
  name: 'workReport',
  components: {
    continer,
    quickSearch,
    instiutionTable
  }
})
export default class WorkReport extends Vue {
  [x: string]: any
  private createCount = 0
  private endCount = 0
  private finishCount = 0
  private trend: number = 0
  private time: any = 'nowWeek'
  private trendList: any[] = [
    {
      label: '周维度',
      value: 0
    },
    {
      label: '月维度',
      value: 1
    },
    {
      label: '年维度',
      value: 2
    },
    {
      label: '自定义时间',
      value: 3
    }
  ]

  private trendOptionList: any[] = [
    [{ label: '本周', value: 'nowWeek' }, { label: '上周', value: 'lastWeek' }, { label: '过去7天', value: 'lastSevenDay' }],
    [{ label: '本月', value: 'nowMonth' }, { label: '上月', value: 'lastMonth' }, { label: '过去30天', value: 'lastTthirtyDay' }],
    [{ label: '今年', value: 'nowYear' }, { label: '去年', value: 'lastYear' }]
  ]

  private quickSearchForm: any = {
    form: {
      dateRange: '',
      modelId: [],
      source: []
    },
    advSearchOptions: [
      { label: '时间维度', inputType: 'slotCom', placeholder: '请输入', name: 'dateRange', clearable: true },
      { label: '工单类型', inputType: 'ele-select', placeholder: '请选择工单类型', name: 'modelId', clearable: true, multiple: true, selectData: [], defaultProp: { label: 'modelName', value: 'id' } },
      { label: '工单来源', inputType: 'ele-select', placeholder: '请选择工单来源', name: 'source', clearable: true, multiple: true, selectData: workSource, defaultProp: { label: 'label', value: 'value' } }
    ]
  }

  private workTableHeader: any[] = [
    { label: '时间', prop: 'showTime' },
    { label: '新建工单', prop: 'createCount' },
    { label: '完成工单', prop: 'finishCount' },
    { label: '终止工单', prop: 'endCount' }
  ]

  private workTableData: any[] = []

  private startAndEnd = {
    start: '',
    end: ''
  }

  private isxAxisMonth: boolean = false

  private workTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 100
  }

  private trendOptions: any = {
    legend: {
      orient: 'vertical',
      left: '20px',
      top: 0,
      icon: 'roundRect',
      width: 600,
      height: 600,
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 12,
      itemStyle: {
        opacity: 1
      },
      textStyle: {
        padding: [0, 0, 0, 5]
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const list: any[] = []
        let listItem: string = ''
        params.forEach(x => {
          list.push(
            `
            <div style="margin:8px 0 8px 0">
              <i style="display: inline-block;width: 6px;height: 6px;background:${x.color};margin-right: 5px;border-radius: 50%;}"></i>` +
              `<span>${x.seriesName}:</span>
              <span style="margin-left: 16px;color:#303753">${x.value}</span>
            </div>
            `
          )
        })
        listItem = list.join('')
        return `<div class="tooltip-conainer">
                  <p style="margin-bottom:8px;color:#303753">${params[0].name}</p>
                  ${listItem}
                </div>`
      }
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    grid: {
      left: 200,
      top: 24,
      bottom: 24
    },
    series: [
      {
        data: [],
        type: 'line',
        name: '新建工单',
        symbol: 'circle',
        symbolSize: 8,
        smooth: true,
        itemStyle: {
          normal: {
            color: '#69D279',
            borderColor: '#ffffff',
            lineStyle: {
              color: '#69D279'
            }
          }
        }
      },
      {
        data: [],
        type: 'line',
        name: '完成工单',
        symbol: 'circle',
        symbolSize: 8,
        smooth: true,
        itemStyle: {
          normal: {
            color: '#3E7FEF',
            borderColor: '#ffffff',
            lineStyle: {
              color: '#3E7FEF'
            }
          }
        }
      },
      {
        data: [],
        type: 'line',
        name: '终止工单',
        symbol: 'circle',
        symbolSize: 8,
        smooth: true,
        itemStyle: {
          normal: {
            color: '#FFBF00',
            borderColor: '#ffffff',
            lineStyle: {
              color: '#FFBF00'
            }
          }
        }
      }
    ]
  }

  private handleTrendChange (val) {
    if (val === 0) {
      if (!['nowWeek', 'lastWeek', 'lastSevenDay'].includes(this.time)) {
        this.time = 'nowWeek'
      }
    } else if (val === 1) {
      if (!['nowMonth', 'lastMonth', 'lastTthirtyDay'].includes(this.time)) {
        this.time = 'nowMonth'
      }
    } else if (val === 2) {
      if (!['nowYear', 'lastYear'].includes(this.time)) {
        this.time = 'nowYear'
      }
    }
    if (val !== 3) {
      this.getTableList()
    }
  }

  private handleTimeChange (val) {
    if (val) {
      this.getTableList()
    }
  }

  private handleDatePickerChange (val) {
    if (val) {
      this.getTableList()
    }
  }

  private getStartAndEnd () {
    const nowFormat = getNowFormatDate()
    if (this.time === 'nowWeek') {
      this.startAndEnd.start = getCurrentWeekFirstDay()
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'lastWeek') {
      this.startAndEnd.start = getLastWeekData().startDay
      this.startAndEnd.end = getLastWeekData().endDay
    } else if (this.time === 'lastSevenDay') {
      this.startAndEnd.start = getLastDate(7)
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'nowMonth') {
      this.startAndEnd.start = getCurrentMonthFirstDay()
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'lastMonth') {
      this.startAndEnd.start = lastMonthFirst()
      this.startAndEnd.end = lastMonthLast()
    } else if (this.time === 'lastTthirtyDay') {
      this.startAndEnd.start = getLastDate(30)
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'nowYear') {
      this.startAndEnd.start = new Date().getFullYear() + '-01-01'
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'lastYear') {
      this.startAndEnd.start = new Date().getFullYear() - 1 + '-01-01'
      this.startAndEnd.end = new Date().getFullYear() - 1 + '-12-31'
    } else {
      this.startAndEnd.start = this.time[0]
      this.startAndEnd.end = this.time[1]
    }
  }

  private getTableList () { // 获取表格数据
    const { modelId, source, dateRange } = this.quickSearchForm.form
    this.getStartAndEnd()
    let start = this.startAndEnd.start + ' 00:00:00'
    let end = this.startAndEnd.end + ' 23:59:59'
    if (Array.isArray(dateRange) && dateRange.length === 2) {
      start = dateRange[0]
      end = dateRange[1]
    }
    const sedData = {
      start,
      end,
      modelId,
      source
    }
    commonAction({
      url: '/server-work/action/report/workOrderTimeTrendReport',
      method: 'post',
      data: sedData
    }).then(res => {
      if (res.success) {
        this.workTableData = res.data || []
        this.createCount = 0
        this.endCount = 0
        this.finishCount = 0
        this.workTableData.forEach(item => {
          this.createCount += item.createCount
          this.endCount += item.endCount
          this.finishCount += item.finishCount
        })
        // 更新图表
        this.getxAxisData()
        this.getSeriesData(this.workTableData)
        this.drawCharts('#workTrend', this.trendOptions)
      }
    })
  }

  private getWorkTypeList () {
    commonAction({
      url: '/server-work/action/workOrderModel/getCategory/filter',
      method: 'post',
      data: { filterPermission: 1 }
    }).then(res => {
      if (res.success) {
        const obj = this.quickSearchForm.advSearchOptions.find(item => item.label === '工单类型')
        if (obj) {
          obj.selectData = res.data
        }
      }
    })
  }

  private headerQuery () {
    this.getTableList()
  }

  private refresh () {
    this.getTableList()
  }

  private drawCharts (dom, option, setting = {}) {
    const node = document.querySelector(dom)
    let myChart = echarts.getInstanceByDom(node)
    if (!myChart) {
      myChart = echarts.init(node, '', setting)
    }
    myChart.setOption(option)
  }

  private getxAxisData () {
    let xArray = getDateGap(this.startAndEnd.start, this.startAndEnd.end)
    this.isxAxisMonth = false
    if (xArray.length > 50) {
      this.isxAxisMonth = true
      xArray = getMonthBetween(this.startAndEnd.start, this.startAndEnd.end)
    }
    this.trendOptions.xAxis.data = [...xArray]
  }

  private getSeriesData (data) {
    const length = this.trendOptions.xAxis.data.length
    this.trendOptions.series.forEach(item => {
      item.data = new Array(length).fill(0)
    })
    data.forEach(item => {
      let index = -1
      if (this.isxAxisMonth) {
        index = this.trendOptions.xAxis.data.findIndex(x => x === item.showTime.substr(0, 7))
        this.trendOptions.series[0].data[index] += item.createCount
        this.trendOptions.series[1].data[index] += item.finishCount
        this.trendOptions.series[2].data[index] += item.endCount
      } else {
        index = this.trendOptions.xAxis.data.findIndex(x => x === item.showTime.substr(0, 10))
        this.trendOptions.series[0].data[index] = item.createCount
        this.trendOptions.series[1].data[index] = item.finishCount
        this.trendOptions.series[2].data[index] = item.endCount
      }
    })
  }

  private mounted () {
    this.getWorkTypeList()
    this.getTableList()
    this.drawCharts('#workTrend', this.trendOptions)
  }
}
</script>

<style lang="stylus" scoped>
.work-trend
  font-family: 'PingFang SC';
  font-style: normal;
  height: 100%
  /deep/.tooltip-conainer
    margin-top 2px
    margin-bottom -6px
  .work-report
    /deep/.pages
      display: none
    /deep/.instiutionTable
      // height: calc(100% - 515px)
      .tableBox
        padding-top 0
    .data-report
      font-weight: 500;
      font-size: 14px;
      margin: 16px 0
    .report-count
      display: flex
      margin-bottom: 35px
      .report:first-child
        margin-left 0
      .report:last-child
        border none
      .report
        flex-basis: 32%
        margin-left 32px
        border-right: 1px solid #ECF0F3
        position relative
        .icon
          float left
          height: 44px
          width: 44px
          border-radius 22px
          margin-top 8px
          margin-right 15px
          .V7_iconfont
            position relative
            top 12px
            left 12px
            font-size 20px
        .title
          line-height: 25px
        .count
          font-weight: 600;
          font-size: 24px;
          line-height: 34px;
    .charts-container
      display flex
      height: 350px
      border 1px solid #ECF0F3
      border-radius: 4px
      .charts
        height: 300px
        width: 100%
        margin auto 0 auto -160px
</style>
